<template>
  <div class="app-container">
    <div class="filter-container">
      <div style="margin-top: 10px">
        <el-row :gutter="20">
          <el-col :offset="5" :span="13">
            <div class="grid-content bg-purple" style="margin-top: 5px">
              <el-input v-model="keywords">
                <template slot="prepend" class="input-with-select">
                  <el-cascader
                    v-model="nation"
                    :options="nationList"
                    :style="{width: '100%'}"
                    :props="{checkStrictly: true}"
                    collapse-tags
                    filterable
                    clearable
                  ></el-cascader>
                </template>
                <template slot="append">
                  <el-button @click="search">
                    立即搜索
                  </el-button>
                </template>
              </el-input>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="grid-content bg-purple">
              <div class="checkbox-group">
                <p>
                  <el-checkbox v-model="listQuery.hideInvalid">隐藏无效客户</el-checkbox>
                </p>
                <p>
                  <el-checkbox v-model="listQuery.hideAdded">隐藏已添加</el-checkbox>
                </p>
                <p>
                  <el-checkbox v-model="listQuery.filterDuplicate">过滤重复</el-checkbox>
                </p>
              </div>
            </div>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <div class="grid-content bg-purple-dark">
              <div>
                <div
                  class="tag-title"
                  style="margin: 5px; display: inline-block"
                >
                  <div
                    style="color:#13ce66;background:#e7faf0;border:1px solid #a1ebc2;padding:10px 20px;font-size:14px;border-radius:4px;">
                    过滤平台 :
                  </div>
                </div>
                <div class="tag-content" style="display: inline-block">
                  <el-select v-model="listQuery.filteredPlatforms" clearable multiple placeholder="请选择"
                             style="width:1000px">
                    <el-option

                      v-for="item in options"
                      :key="item"
                      :label="item"
                      :value="item">
                    </el-option>
                  </el-select>
                </div>
                <div
                  class="tag-button"
                  style="margin: 5px; display: inline-block"
                >
                  <el-button type="warning" plain size="small" @click="defaultFilter">默认过滤</el-button>
                  <el-button type="warning" plain size="small" @click="showAddFilterPlatform">设置</el-button>
                  <el-select size="small" v-model="listQuery.contains" :style="{width: '80px',marginLeft: '10px'}">
                    <el-option :value="false" label="排除"></el-option>
                    <el-option :value="true" label="包含"></el-option>
                  </el-select>
                </div>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
    </div>

    <el-table
      ref="multipleTable"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      default-expand-all
      :height="total>0 ? 'calc(100vh - 300px)' : 'calc(100vh - 260px)'"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" align="center"/>
      <el-table-column type="expand">
        <template slot-scope="{row}">
          <el-form v-if="row.details" label-position="left" inline class="demo-table-expand">
            <div class="form-group">
              <el-form-item v-if="row.details.facebook_url">
                <template slot="label">
                  <svg-icon name="facebook" style="font-size: 2rem;" original/>
                </template>
                <el-link target="_blank" :href="row.details.facebook_url" v-html="row.details.facebook_username"></el-link>
              </el-form-item>
              <el-form-item v-if="row.details.twitter_url">
                <template slot="label">
                  <svg-icon name="twitter" style="font-size: 2rem;" original/>
                </template>
                <el-link target="_blank" :href="row.details.twitter_url">{{ row.details.twitter_username }}</el-link>
              </el-form-item>
              <el-form-item v-if="row.details.google_plus_url">
                <template slot="label">
                  <svg-icon name="google-plus" style="font-size: 2rem;" original/>
                </template>
                <el-link target="_blank" :href="row.details.google_plus_url">{{ row.details.google_plus_username }}</el-link>
              </el-form-item>
              <el-form-item v-if="row.details.youtube_url">
                <template slot="label">
                  <svg-icon name="youtube" style="font-size: 2rem;" original/>
                </template>
                <el-link target="_blank" :href="row.details.youtube_url">{{ row.details.youtube_username }}</el-link>
              </el-form-item>
              <el-form-item v-if="row.details.instagram_url">
                <template slot="label">
                  <svg-icon name="instagram" style="font-size: 2rem;" color="#f54832 #fff"/>
                </template>
                <el-link target="_blank" :href="row.details.instagram_url">{{ row.details.instagram_username }}</el-link>
              </el-form-item>
              <el-form-item v-if="row.details.linkedin_url">
                <template slot="label">
                  <svg-icon name="linkedin" style="font-size: 2rem;" original/>
                </template>
                <el-link target="_blank" :href="row.details.linkedin_url">{{ row.details.linkedin_username }}</el-link>
              </el-form-item>
              <el-form-item v-if="row.details.github_url">
                <template slot="label">
                  <svg-icon name="github" style="font-size: 2rem;" original/>
                </template>
                <el-link target="_blank" :href="row.details.github_url">{{ row.details.github_username }}</el-link>
              </el-form-item>
            </div>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column align="center" label="序号" width="50">
        <template slot-scope="{$index}">
          {{ $index + 1 }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="域名" min-width="75">
        <template slot-scope="{row}">
          <el-link target="_blank" :href="row.url">{{ row.domain }}</el-link>
        </template>
      </el-table-column>
      <el-table-column align="center" label="标题" min-width="100" prop="title"/>
      <el-table-column align="center" label="描述" min-width="200" prop="description"/>
<!--      <el-table-column align="left" label="联系电话" min-width="120" prop="details.phones">-->
<!--        <template slot-scope="{row}">-->
<!--          <template v-if="row.details && row.details.phones">-->
<!--            <div v-for="(phone, index) in row.details.phones.split(',')" :key="index">-->
<!--              <template v-if="index < 5">-->
<!--                <el-link icon="el-icon-mobile-phone"  @click="handleClipboard(phone, $event)">{{ phone }}</el-link>-->
<!--              </template>-->
<!--            </div>-->
<!--          </template>-->
<!--          <template v-else>-->
<!--            暂无信息-->
<!--          </template>-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column align="left" label="邮箱" min-width="180" prop="details.company_email">-->
<!--        <template slot-scope="{row}">-->
<!--          <template v-if="row.details && row.details.company_email">-->
<!--            <div v-for="(email, index) in row.details.company_email.split(',')" :key="index">-->
<!--              <template v-if="index < 5">-->
<!--                <el-link icon="el-icon-message"  @click="handleClipboard(email, $event)">{{ email }}</el-link>-->
<!--              </template>-->
<!--            </div>-->
<!--          </template>-->
<!--          <template v-else>-->
<!--            暂无信息-->
<!--          </template>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column align="center" width="290">
        <template slot="header">
          <el-dropdown>
            <span>
              批量操作<i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item icon="el-icon-plus" @click.native="batchAddCustomers">批量添加</el-dropdown-item>
<!--              <el-dropdown-item icon="el-icon-circle-plus"-->
<!--              >批量挖掘-->
<!--              </el-dropdown-item-->
<!--              >-->
            </el-dropdown-menu>
          </el-dropdown>
        </template>
        <template slot-scope="{row}">
          <el-button size="mini" type="primary" plain @click="showDetail(row)">查看详情</el-button>
          <el-button type="success" size="mini" plain :disabled="row.isAdded" @click="addCustomers(row)">
            {{ row.isAdded ? '已添加' : '添加客户' }}
          </el-button>
          <!--          <el-button size="mini">深度挖掘</el-button>-->
          <el-button plain :disabled="row.isInvalid" type="danger" size="mini" @click="addPublicCustomers(row)">
            {{ row.isInvalid ? '已无效' : '无效客户' }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
        <pagination
          v-show="list.length>0"
          :total="total"
          :page.sync="listQuery.page"
          :limit.sync="listQuery.limit"
          :page-sizes="[10]"
          @pagination="search"
        />
    <add-filter-platform :show.sync="showAddFilterPlatformState" @submit="handleAddFilterPlatform"/>
    <Details :show.sync="showDetailsState" :id="selectId"></Details>
  </div>
</template>

<script lang="ts">
import { Component, Inject, Vue, Watch } from 'vue-property-decorator'
import Btn from '@/views/data-search/btn.vue'
import AddFilterPlatform from '@/views/data-search/add-filter-platform.vue'
import { getAction, getLongTimeAction, postAction, postLongTimeAction } from '@/api/common'
import Details from '@/views/data-search/details.vue'
import Pagination from '@/components/Pagination/index.vue'
import { handleClipboard } from '@/utils/clipboard'

@Component({
  name: 'globalEngine',
  components: { Details, Btn, AddFilterPlatform, Pagination },
  inject: ['showProgressDialog']
})
export default class extends Vue {
  private list: any[] = [];
  private total = 0;
  private searchLoading = false
  private nationLoading = false
  private listQuery = {
    hideInvalid: true,
    hideAdded: true,
    filterDuplicate: true,
    filteredPlatforms: [''],
    page: 1,
    limit: 10,
    contains: false
  };

  private showAddFilterPlatformState = false;
  private showDetailsState = false;
  private multipleSelection: any[] = [];
  private options: any[] = []
  private baseOptions = ['baidu.com',
    'google.com',
    'bing.com',
    'yahoo.com',
    'facebook.com',
    'aol.com',
    'amazon.com',
    'ebay.com',
    'youtube.com',
    'msn.com',
    'aliexpress.com',
    'alibaba.com',
    'shopee.com',
    'lazada.com',
    'yandex.com',
    'twitter.com',
    'linkedin.com',
    'instagram.com'

  ]

  private nation: number[] = []
  private keywords = ''
  private nationList: any[] = []
  private selectId = 0
  private handleClipboard = handleClipboard
  @Inject('showProgressDialog') private showProgressDialog: any

  get listLoading() {
    return this.searchLoading || this.nationLoading
  }

  async init() {
    await this.fetchNationList()
    this.defaultFilter()
    let nation : any = this.$route.query.nation
    const keywords = this.$route.query.keywords
    // let { nation, keywords } = this.$route.query
    if (nation && typeof keywords === 'string') {
      if (typeof nation === 'string') nation = nation.split(',').map(m => parseInt(m))
      this.nation = nation as number[]
      this.keywords = keywords
      this.search()
      // 清除query
      this.$router.push({ query: {} })
    }
  }

  created() {
    this.init()
  }

  @Watch('$route.query', { deep: true })
  watchQuery(val: any) {
    console.log(val)
    if (val.nation) {
      this.init()
    }
  }

  private handleSelectionChange(value: any) {
    this.multipleSelection = value
  }

  async search() {
    this.searchLoading = true
    getLongTimeAction({
      nation: this.nation[0],
      keywords: this.keywords,
      ...this.listQuery
    }, 'globalSearch').then(res => {
      this.list = res.data.domainList.items
      this.total = res.data.domainList.total
    }).finally(() => {
      this.searchLoading = false
    })
    // const _list = []
    // for (const key of Object.keys(res)) {
    //   _list.push(...res[key])
    // }
  }

  private async fetchNationList() {
    this.nationLoading = true
    getAction(null, 'globalSearch/GetInit').then(res => {
      const rec = (m:any) : any => {
        if (m.children) {
          return ({ label: m.geoNameCn, value: m.id, children: m.children.map(rec) })
        }
        return ({ label: m.geoNameCn, value: m.id })
      }
      this.nationList = res.data.nationList?.map(rec) ?? []
    }).finally(() => {
      this.nationLoading = false
    })
  }

  async showDetail(row: any) {
    this.showDetailsState = true
    this.selectId = row.id
  }

  addCustomers(row: any) {
    if (this.searchLoading) return
    this.searchLoading = true

    postLongTimeAction(null, `Customer/DataSearchCreate/${row.id}?isPrivate=1`)
      .then(res => {
        this.$message.success('操作成功')
        this.search()
      }).catch(e => {
        this.$message.error(e.message)
        this.searchLoading = false
      })
  }

  batchAddCustomers() {
    if (this.searchLoading) return
    this.searchLoading = true

    const selectedRows: number[] = this.multipleSelection.map(m => m.id)
    if (selectedRows.length === 0) {
      this.$message.warning('请先选择数据')
      this.searchLoading = false
      return false
    }

    const uploadItems = [
      { name: '数据', num: this.multipleSelection.length, action: this.batchAddFunc, data: this.multipleSelection }
    ]
    const uploadColumns = [
      { label: '域名', key: 'domain', popover: true }
    ]

    this.showProgressDialog(uploadItems, uploadColumns, this.search, { title: '批量添加客户' })
  }

  async batchAddFunc({ item, message } : any) {
    postLongTimeAction(null, 'Customer/DataSearchCreate/' + item.id + '?isPrivate=1')
      .then(res => {
        message.success('[' + item.domain + '] 添加成功')
      }).catch(e => {
        message.failed('[' + item.domain + '] ' + e.message)
      })
  }

  addPublicCustomers(row: any) {
    if (this.searchLoading) return
    this.searchLoading = true

    postLongTimeAction(null, 'Customer/DataSearchCreate/' + row.id)
      .then(res => {
        this.$message.success('操作成功')
        this.search()
      }).catch(e => {
        this.$message.error(e.message)
        this.searchLoading = false
      })
  }

  defaultFilter() {
    this.options = [...this.baseOptions]
    this.listQuery.filteredPlatforms = [...this.options]
  }

  showAddFilterPlatform() {
    this.showAddFilterPlatformState = true
  }

  handleAddFilterPlatform(platforms: string[]) {
    for (const platform of platforms) {
      if (this.options.indexOf(platform) === -1) {
        this.options.push(platform)
        this.listQuery.filteredPlatforms.push(platform)
      }
    }
  }
}
</script>

<style scoped>
.checkbox-group {
  margin-left: 100px;
}

.checkbox-group > p {
  margin: 0px 0px 0px 0px;
}

.el-tag + .el-tag {
  margin-left: 10px;
}

.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}

.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}

.el-input::v-deep .el-input-group__prepend {
  padding: 0;
  width: 200px;
  border: unset;
}

.el-cascader::v-deep .e-input {
  margin-top: -1px;
}

/* .el-input::v-deep .el-input-group__prepend >div.el-cascader.el-cascader--medium.el-cascader >div.el-input.el-input--medium.el-input--suffix > .el-input__inner{ */
/* border-right: unset; */
/* } */

.el-table::v-deep .el-table__expanded-cell[class*=cell] {
  padding: 0;
}
.demo-table-expand::v-deep .el-form-item {
  padding: 20px 0 0;
}
.form-group .el-form-item:first-child {
  padding-left: 30px;
}
</style>
